package com.hbue.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbue.springboot.mapper.ManageCustomerMapper;
import com.hbue.springboot.mapper.TbAccountMapper;
import com.hbue.springboot.pojo.TbAccount;
import com.hbue.springboot.pojo.TbCustomer;
import com.hbue.springboot.service.ManageCustomerService;
import com.hbue.springboot.utils.QueryParams;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class ManageCustomerServiceImpl extends ServiceImpl<ManageCustomerMapper, TbCustomer> implements ManageCustomerService {

    private final TbAccountMapper tbAccountMapper;

    private final ManageCustomerMapper manageCustomerMapper;

    public List<TbCustomer> getAllCustomers() {
        return manageCustomerMapper.selectList(new QueryWrapper<TbCustomer>());
    }

    public int addCustomer(TbCustomer customer) {
        TbAccount account = new TbAccount();
        account.setUserName(customer.getCustName());
        account.setUserPwd(DigestUtils.md5DigestAsHex("admin".getBytes()));
        account.setUserRole(2);
        if(customer.getCustAddress() != null) {
            account.setUserEmail(customer.getCustAddress());
        }
        if(customer.getCustMobile() != null) {
            account.setUserMobile(customer.getCustMobile());
        }
        if(tbAccountMapper.insert(account) <= 0) {
            return -1;
        }
        return manageCustomerMapper.insert(customer);
    }

    public int deleteCustomer(int id) {
        return manageCustomerMapper.deleteById(id);
    }

    public int updateCustomer(TbCustomer customer) {
        return manageCustomerMapper.updateById(customer);
    }

    public List<TbCustomer> getCustomerByName(String customerName) {
        return manageCustomerMapper.getCustomerByName(customerName);
    }

    public IPage<TbCustomer> listCustomer(QueryParams queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        IPage<TbCustomer> page = new Page<>(pageNum , pageSize);
        return manageCustomerMapper.selectPage(page, null);
    }
}
